Puzzle 7 Explanation: NaN
Understand how float numbers can be different from calculated numbers.
We'll cover the following
Try it yourself#
Try executing the code below to see the result for yourself.
Explanation#
You might have expected 1.21, which is the right mathematical answer.
When seeing this or similar output, some new developers come to the message boards and say, “We found a bug in Go!” The usual answer is, “Read the manual” (RTM).
According to Grant Edwards, “Floating point is sort of like quantum physics: the closer you look, the messier it gets.”
The basic idea behind this issue is that in floating points, we sacrifice accuracy for speed. Don’t be shocked; it’s a trade-off we often do in computer science.
The result we see conforms with the floating-point specification. If we run the same code in Python, Java, C … you will see the same output.
Remember that floating-point numbers are not accurate, and accuracy worsens as the number gets bigger. One implication is that, when testing with floating points, we need to check for “roughly equal” and decide on an acceptable threshold. Testing libraries such as stretchr/testify have ready-made functions (such as InDelta) to check if two floating numbers are approximately equal.
Floating points have several other oddities. For example, there’s a particular NaN value (short for “not a number”). The NaN value does not equal any number, including itself. The following code prints false:
fmt.Println(math.NaN() == math.NaN())
Note: To verify if you get
NaN, you need to use a special function such asmath.IsNaN. If you need better accuracy, look intomath/bigor external packages such asshopspring/decimal.
Puzzle 7: Can Numbers Lie?
Puzzle 8: Sleep Sort